﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using Lists;
using GeneralLibs;

namespace BI.BIKPI
{
    public partial class FrmBaoCaoHangBanChayNhat : BasicForms.FrmSupportPrintableComponents
    {
        public FrmBaoCaoHangBanChayNhat()
        {
            InitializeComponent();
        }

        private void FrmThongKeNhapXuatTon_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
            try
            {
                cmbNhomVatTuHangHoa.DataSource = DanhMucNhomVatTuHangHoa.Instance.DataView;
                cmbNhomVatTuHangHoa.DisplayColumn = "Ten";
                cmbNhomVatTuHangHoa.ValueColumn = "ID";
                cmbNhomVatTuHangHoa.AddVisibleColumn("Ma", "Mã");
                cmbNhomVatTuHangHoa.AddVisibleColumn("Ten", "Tên");
                if (dsThongKe == null) dsThongKe = new BaoCaoHangBanChayNhat.DsBaoCaoHangBanChayNhat();

                cmbKyBaoCao.SelectedText = "Tùy chọn";
            }
            catch (Exception ex)
            {
            }

            try
            {
                foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
                {
                    column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
                }
                //foreach (DataRow row in dsThongKe.VatTuHangHoa.Rows)
                //{
                //    row["Choose"] = false;
                //}
                FormatNumberInGridView(gridView);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void cmbNhomVatTuHangHoa_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbNhomVatTuHangHoa.EditValue = Guid.Empty;
        }
        private void cmbNhomVatTuHangHoa_EditValueChanged(object sender, EventArgs e)
        {
            //if (!(cmbNhomVatTuHangHoa.EditValue is Guid) || (Guid)cmbNhomVatTuHangHoa.EditValue == Guid.Empty) return;
            try
            {
                if (cmbNhomVatTuHangHoa.EditValue is Guid && (Guid)cmbNhomVatTuHangHoa.EditValue != Guid.Empty)
                {
                    //Dieu kien loc la ID = cmbNhomVatTuHangHoa.EditValue + ID cac nhom con.
                    string filterNhomCon = "CONVERT('{" + cmbNhomVatTuHangHoa.EditValue.ToString() + "}','System.Guid'), ";
                    DanhMucNhomVatTuHangHoa cacNhomCon = DanhMucNhomVatTuHangHoa.Instance.GetNhomVatTuHangHoaCon((Guid)cmbNhomVatTuHangHoa.EditValue);
                    foreach (NhomVatTuHangHoa nhomCon in cacNhomCon)
                    {
                        filterNhomCon += "CONVERT('{" + nhomCon.ID + "}','System.Guid'), ";
                        //filterNhomCon += string.Format(", '{0}'", nhomCon.ID);
                    }
                    if (filterNhomCon.EndsWith(", ")) filterNhomCon = filterNhomCon.Remove(filterNhomCon.Length - 2);

                }
                else
                {
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private DataTable GetHangDaCoGiaoDich(SqlCommand cmd, Guid selectedKhoID, DateTime ngayKetThuc)
        {
            try
            {
                ThoiDiemKhoaSo thoiDiemKhoaSo = DanhMucThoiDiemKhoaSo.Instance.GetThoiDiemChotSoDuGanNhat(ngayKetThuc);
                if (selectedKhoID != null && selectedKhoID != Guid.Empty)
                {
                    cmd.CommandText = string.Format("SELECT DISTINCT A.VatTuHangHoaID, KhoID, B.NhomVatTuHangHoaID \n" +
                                                    "FROM NhatKyKho A INNER JOIN VatTuHangHoa B ON B.ID = A.VatTuHangHoaID \n" +
                                                    "WHERE  KhoID = @KhoID AND @ThoiDiemDau <= Ngay AND Ngay <= @ThoiDiemCuoi \n" +
                                                    "   AND A.VatTuHangHoaID is not null  \n" +
                                                    "UNION \n" +
                                                    "SELECT DISTINCT A.VatTuHangHoaID, KhoID, B.NhomVatTuHangHoaID \n" +
                                                    "FROM TonKho A INNER JOIN VatTuHangHoa B ON B.ID = A.VatTuHangHoaID  \n" +
                                                    "WHERE KhoID = @KhoID AND SoLuong <> 0 \n" +
                                                    "   AND A.VatTuHangHoaID is NOT NULL");
                    cmd.Parameters.Clear();
                    cmd.Parameters.AddWithValue("KhoID", selectedKhoID);
                    cmd.Parameters.AddWithValue("ThoiDiemDau", thoiDiemKhoaSo.ThoiDiem);
                    cmd.Parameters.AddWithValue("ThoiDiemCuoi", ngayKetThuc);
                }
                else
                {
                    cmd.CommandText = string.Format("SELECT DISTINCT A.VatTuHangHoaID, B.NhomVatTuHangHoaID \n" +
                                              "FROM NhatKyKho A INNER JOIN VatTuHangHoa B ON B.ID = A.VatTuHangHoaID \n" +
                                              "WHERE  @ThoiDiemDau <= Ngay AND Ngay <= @ThoiDiemCuoi  \n" +
                                              "	AND A.VatTuHangHoaID is NOT NULL \n" +
                                              "UNION \n" +
                                              "SELECT DISTINCT VatTuHangHoaID, B.NhomVatTuHangHoaID  \n" +
                                              "FROM TonKho A INNER JOIN VatTuHangHoa B ON B.ID = A.VatTuHangHoaID  \n" +
                                              "WHERE SoLuong <> 0 \n" +
                                              "	AND A.VatTuHangHoaID is NOT NULL ");

                    cmd.Parameters.Clear();
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("ThoiDiemDau", thoiDiemKhoaSo.ThoiDiem);
                    cmd.Parameters.AddWithValue("ThoiDiemCuoi", ngayKetThuc);
                }
                DataTable dtDaCoGiaoDich = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dtDaCoGiaoDich);
                return dtDaCoGiaoDich;
            }
            catch (Exception ex)
            {
                string message = string.Format("Lỗi [{0}] ở \n {1}", ex.Message, ex.StackTrace.Substring(0, ex.StackTrace.IndexOf("\n")));
                throw new CustomException(message);
                return null;
            }
        }

        private DataTable GetToanBoHangDangSuDung(SqlCommand cmd, Guid selectedKhoID, DateTime ngayKetThuc)
        {
            try
            {
                ThoiDiemKhoaSo thoiDiemKhoaSo = DanhMucThoiDiemKhoaSo.Instance.GetThoiDiemChotSoDuGanNhat(ngayKetThuc);
                if (selectedKhoID != null && selectedKhoID != Guid.Empty)
                {
                    cmd.CommandText = string.Format("SELECT DISTINCT A.VatTuHangHoaID, KhoID, B.NhomVatTuHangHoaID \n" +
                                                    "FROM NhatKyKho A INNER JOIN VatTuHangHoa B ON B.ID = A.VatTuHangHoaID  \n" +
                                                    "WHERE  KhoID = @KhoID AND @ThoiDiemDau <= Ngay AND Ngay <= @ThoiDiemCuoi \n" +
                                                    "   AND A.VatTuHangHoaID is not null  \n" +
                                                    "UNION \n" +
                                                    "SELECT DISTINCT A.VatTuHangHoaID, KhoID, B.NhomVatTuHangHoaID \n" +
                                                    "FROM TonKho A INNER JOIN VatTuHangHoa B ON B.ID = A.VatTuHangHoaID  \n" +
                                                    "WHERE KhoID = @KhoID AND SoLuong <> 0 \n" +
                                                    "   AND A.VatTuHangHoaID is NOT NULL");
                    cmd.Parameters.Clear();
                    cmd.Parameters.AddWithValue("KhoID", selectedKhoID);
                    cmd.Parameters.AddWithValue("ThoiDiemDau", thoiDiemKhoaSo.ThoiDiem);
                    cmd.Parameters.AddWithValue("ThoiDiemCuoi", ngayKetThuc);
                }
                else
                {

                    cmd.CommandText = string.Format("SELECT DISTINCT VatTuHangHoaID, B.NhomVatTuHangHoaID \n" +
                                                    "FROM NhatKyKho A INNER JOIN VatTuHangHoa B ON B.ID = A.VatTuHangHoaID \n" +
                                                    "WHERE  @ThoiDiemDau <= Ngay AND Ngay <= @ThoiDiemCuoi  \n" +
                                                    "	AND A.VatTuHangHoaID is NOT NULL \n" +
                                                    "UNION \n" +
                                                    "SELECT DISTINCT VatTuHangHoaID, B.NhomVatTuHangHoaID \n" +
                                                    "FROM TonKho A INNER JOIN VatTuHangHoa B ON B.ID = A.VatTuHangHoaID  \n" +
                                                    "WHERE SoLuong <> 0 \n" +
                                                    "	AND A.VatTuHangHoaID is NOT NULL ");

                    cmd.Parameters.Clear();
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("ThoiDiemDau", thoiDiemKhoaSo.ThoiDiem);
                    cmd.Parameters.AddWithValue("ThoiDiemCuoi", ngayKetThuc);
                }
                DataTable dtDaCoGiaoDich = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dtDaCoGiaoDich);
                return dtDaCoGiaoDich;
            }
            catch (Exception ex)
            {
                string message = string.Format("Lỗi [{0}] ở \n {1}", ex.Message, ex.StackTrace.Substring(0, ex.StackTrace.IndexOf("\n")));
                throw new CustomException(message);
                return null;
            }
        }
            
        private void btnLoad_Click(object sender, EventArgs e)
        {
            DateTime ngayBatDau = dtNgayBatDau.DateTime;
            DateTime ngayKetThuc = dtNgayKetThuc.DateTime;
            if(!(FrmThamSoBaoCao.CheckKyBaoCaoVaThoiDiemKhoaSo(dtNgayBatDau, dtNgayKetThuc))) return;
            ThoiDiemKhoaSo thoiDiemKhoaSoGanNhat = DanhMucThoiDiemKhoaSo.Instance.GetThoiDiemKhoaSoGanNhat(ngayKetThuc);

            BasicForms.FrmProgressBar.StartShowProgress();
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();

                string vatTuHangHoaCondition ="";
                if (cmbNhomVatTuHangHoa.Text == "")
                    vatTuHangHoaCondition = "1=1";
                else
                    vatTuHangHoaCondition = string.Format("NhomVatTuHangHoaID = '{0}'", cmbNhomVatTuHangHoa.EditValue);

                if (nmrThresholds.Text != "")
                {
                    if (rdoSapSoLuong.Checked)
                        cmd.CommandText = string.Format("SELECT TOP {2} B.Ma, B.Ten, B.GiaBia, B.NhomVatTuHangHoaID, CAST(SUM(SoLuong) AS decimal) SoLuongBan, CAST(SUM(ThanhTienQD) AS decimal) AS ThanhTienBan \n" +
                                                 "FROM NhatKyXuatKho A INNER JOIN VatTuHangHoa B ON A.VatTuHangHoaID = B.ID \n" +
                                                 "WHERE LoaiChungTuGocID IN('{0}', '{1}') AND @ThoiDiemDau <  Ngay AND Ngay < @ThoiDiemCuoi \n" +
                                                 "GROUP BY B.Ma, B.Ten, B.GiaBia, B.NhomVatTuHangHoaID  \n" +
                                                 "ORDER BY SoLuongBan DESC ",
                                                 DanhMucLoaiChungTu.Instance.GetByMa("HoaDonBanHang").ID, DanhMucLoaiChungTu.Instance.GetByMa("HoaDonBanLe").ID,
                                                 nmrThresholds.Text);
                    else
                        cmd.CommandText = string.Format("SELECT TOP {2} B.Ma, B.Ten, B.GiaBia, B.NhomVatTuHangHoaID, CAST(SUM(SoLuong) AS decimal) SoLuongBan, CAST(SUM(ThanhTienQD) AS decimal) AS ThanhTienBan \n" +
                                                 "FROM NhatKyXuatKho A INNER JOIN VatTuHangHoa B ON A.VatTuHangHoaID = B.ID \n" +
                                                 "WHERE LoaiChungTuGocID IN('{0}', '{1}') AND @ThoiDiemDau <  Ngay AND Ngay < @ThoiDiemCuoi \n" +
                                                 "GROUP BY B.Ma, B.Ten, B.GiaBia, B.NhomVatTuHangHoaID  \n" +
                                                 "ORDER BY ThanhTienBan DESC ",
                                                 DanhMucLoaiChungTu.Instance.GetByMa("HoaDonBanHang").ID, DanhMucLoaiChungTu.Instance.GetByMa("HoaDonBanLe").ID,
                                                 nmrThresholds.Text);
                }
                else
                {
                    if (rdoSapSoLuong.Checked)
                        cmd.CommandText = string.Format("SELECT B.Ma, B.Ten, B.GiaBia, B.NhomVatTuHangHoaID, CAST(SUM(SoLuong) AS decimal) SoLuongBan, CAST(SUM(ThanhTienQD) AS decimal) AS ThanhTienBan \n" +
                                             "FROM NhatKyXuatKho A INNER JOIN VatTuHangHoa B ON A.VatTuHangHoaID = B.ID \n" +
                                             "WHERE LoaiChungTuGocID IN('{0}', '{1}') AND @ThoiDiemDau <  Ngay AND Ngay < @ThoiDiemCuoi \n" +
                                             "GROUP BY B.Ma, B.Ten, B.GiaBia, B.NhomVatTuHangHoaID  \n" +
                                             "ORDER BY SoLuongBan DESC ",
                                             DanhMucLoaiChungTu.Instance.GetByMa("HoaDonBanHang").ID, DanhMucLoaiChungTu.Instance.GetByMa("HoaDonBanLe").ID);
                    else
                        cmd.CommandText = string.Format("SELECT B.Ma, B.Ten, B.GiaBia, B.NhomVatTuHangHoaID, CAST(SUM(SoLuong) AS decimal) SoLuongBan, CAST(SUM(ThanhTienQD) AS decimal) AS ThanhTienBan \n" +
                                            "FROM NhatKyXuatKho A INNER JOIN VatTuHangHoa B ON A.VatTuHangHoaID = B.ID \n" +
                                            "WHERE LoaiChungTuGocID IN('{0}', '{1}') AND @ThoiDiemDau <  Ngay AND Ngay < @ThoiDiemCuoi \n" +
                                            "GROUP BY B.Ma, B.Ten, B.GiaBia, B.NhomVatTuHangHoaID  \n" +
                                            "ORDER BY ThanhTienBan DESC ",
                                            DanhMucLoaiChungTu.Instance.GetByMa("HoaDonBanHang").ID, DanhMucLoaiChungTu.Instance.GetByMa("HoaDonBanLe").ID);
                }


                cmd.Parameters.Clear();
                cmd.Parameters.Add(new SqlParameter("ThoiDiemDau", SqlDbType.DateTime));
                cmd.Parameters["ThoiDiemDau"].Value = ngayBatDau;
                cmd.Parameters.Add(new SqlParameter("ThoiDiemCuoi", SqlDbType.DateTime));
                cmd.Parameters["ThoiDiemCuoi"].Value = ngayKetThuc;

                dsThongKe.Detail.Clear();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dsThongKe.Detail);
                dsThongKe.Detail.DefaultView.RowFilter = vatTuHangHoaCondition;
                DataTable dtResult = dsThongKe.Detail.DefaultView.ToTable();

                gridControl.DataSource = dtResult;

                if (rdoSapSoLuong.Checked)
                {
                    //colSoLuongXuat.SortMode = DevExpress.XtraGrid.ColumnSortMode.Value;
                    //colSoLuongXuat.SortOrder = DevExpress.Data.ColumnSortOrder.Descending;
                    colThanhTien.SortOrder = DevExpress.Data.ColumnSortOrder.None;
                }
                else
                {
                    //colThanhTien.SortMode = DevExpress.XtraGrid.ColumnSortMode.Value;
                    //colThanhTien.SortOrder = DevExpress.Data.ColumnSortOrder.Descending;
                    colSoLuongXuat.SortOrder = DevExpress.Data.ColumnSortOrder.None;
                }

                FormatNumberInGridView(gridView);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                FormatNumberInGridView(gridView);
                con.Close();
                con = null;
            }
            BasicForms.FrmProgressBar.FinishShowProgress();
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            PrintWithHeaderAndFooter(false, gridControl, true, true, "Thống kê chi tiết nhập xuất tồn", "", "", "", "");
        }

        private void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                FrmThamSoBaoCao.ThietLapKhoangThoiGianBaoCao(cmbKyBaoCao.Text, cmbKyBaoCao, dtNgayBatDau, dtNgayKetThuc);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
    }
}
